package com.andova.cameraview;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

class CameraFrame implements Handler.Callback {
    private Handler mHandler;
    private HandlerThread mThread;
    private CameraViewImpl.Callback mCallback;
    private volatile boolean mlock = false;

    public void start(CameraViewImpl.Callback callback) {
        mCallback = callback;
        mThread = new HandlerThread("CameraFrame");
        mThread.start();
        mHandler = new Handler(mThread.getLooper(), this);
    }

    public void stop() {
        mThread.quitSafely();
        try {
            mThread.join();
            mThread = null;
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mCallback = null;
        mlock = false;
    }

    public void sendPrevFrame(@Nullable byte[] data) {
        if (data == null || mHandler == null) return;
        if (mlock) return;
        mlock = true;
        Message msg = Message.obtain();
        msg.obj = data;
        mHandler.sendMessage(msg);
    }

    @Override
    final public boolean handleMessage(@NonNull Message message) {
        if (mCallback == null) return false;
        byte[] data = (byte[]) message.obj;
        mCallback.onPrevFrame(data);
        mCallback.onPictTaken(data);
        mlock = false;
        return true;
    }
}
